package com.jbeer.framework.web.viewrender;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.jbeer.framework.JBeer;
import com.jbeer.framework.exception.RenderingViewException;
import com.jbeer.framework.web.ModelAndView;

/**
 * 
 * 
 * @author bieber
 * @version $Id: JSONPRender.java, v 0.1 2014年4月24日 下午5:51:32 bieber Exp $
 */
public class JSONPRender {
    public static void render(HttpServletRequest request,HttpServletResponse response,ModelAndView modelView) throws RenderingViewException{
        try{
            ObjectMapper mapper = new ObjectMapper();
            if(modelView.getData()==null){
                throw new RenderingViewException("No data for rendering");
            }
            String retMsg = null;
            retMsg = mapper.writeValueAsString(modelView.getData());  
            StringBuffer sb = new StringBuffer(modelView.getCallback());
            sb.append("(").append(retMsg).append(");");
            response.setContentType("Content-Type:text/javascript;charset="+JBeer.applicationEncode);
            Writer writer = response.getWriter();
            writer.write(sb.toString());
            writer.flush();
            writer.close();
        }catch(Exception e){
            throw new RenderingViewException(e);
        }
        }
}
